package com.yoso.shop.interfaces.controller.user;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.yoso.base.infrastructure.constants.ErrorMsg;
import com.yoso.base.interfaces.controller.BaseController;
import com.yoso.base.interfaces.controller.BaseResponse;
import com.yoso.base.service.IBaseService;
import com.yoso.shop.application.service.IAdminService;
import com.yoso.shop.domain.user.AdminEntity;
import com.yoso.shop.domain.user.AdminEntityExample;
import com.yoso.shop.interfaces.vo.user.AdminVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;


/**
 * @author shizejin
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "管理员")
@Slf4j
@CrossOrigin
public class AdminInfoController extends BaseController<AdminVo, AdminEntity> {

    @Autowired
    private IAdminService adminService;

    @Override
    public AdminEntity V2E(AdminVo data) {
        return JSON.parseObject(JSON.toJSONString(data), AdminEntity.class);
    }

    @Override
    public AdminVo E2V(AdminEntity data) {
        return JSON.parseObject(JSON.toJSONString(data), AdminVo.class);
    }

    @Override
    public IBaseService<AdminVo, AdminEntityExample> getService() {
        return this.adminService;
    }

    /**
     * 管理员的登录
     */
    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public BaseResponse<Void> login(@RequestBody AdminVo admin) {
        AdminVo result = adminService.login(admin);
        return !ObjectUtils.isEmpty(result) ? this.success("验证成功") : this.error("验证失败");
    }

    @ApiOperation("管理员新增/修改")
    @Override
    public BaseResponse saveOrUpdate(@RequestBody AdminVo admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        if (StringUtils.isAnyBlank(username, password)) {
            return this.error("用户名和密码" + ErrorMsg.MUST_NOT_NULL);
        }
        if (StringUtils.isBlank(admin.getId())) {
            admin.setCreatTime(DateUtil.now());
        }
        admin.setUpdateTime(DateUtil.now());
        admin.setPassword(SecureUtil.md5(password));
        return this.result(this.getService().insert(admin));
    }
}
